<template>
	<div ref="el" class="my-editor-area" :style="{ width, height }"></div>
</template>

<script setup name="MyMonacoEditor">
import { useMonacoEditor } from './index.hook';

const props = defineProps({
	width: {
		type: String,
		default: '100%'
	},
	height: {
		type: String,
		default: '100px'
	},
	language: {
		type: String,
		default: 'typescript'
	},
	preComment: {
		type: String,
		default: ''
	},
	modelValue: {
		type: String,
		default: ''
	},
	editorOptions: {
		type: Object,
		default: () => ({})
	}
});

const emits = defineEmits(['blur', 'update:modelValue']);

const { el, updateVal, getEditor, createEditor } = useMonacoEditor(props.language);

const updateMonacoVal = (_val) => {
	const { modelValue, preComment } = props;
	const val = preComment ? `${preComment}\n${_val || modelValue}` : _val || modelValue;
	updateVal(val);
};

onMounted(() => {
	const monacoEditor = createEditor(props.editorOptions);
	monacoEditor?.onDidChangeModelContent(() => {
		// emits('update:modelValue', monacoEditor?.getValue());
	});
	monacoEditor?.onDidBlurEditorText(() => {
		emits('update:modelValue', monacoEditor?.getValue());
		emits('blur');
	});
	updateMonacoVal();
});

watch(
	() => props.modelValue,
	(val) => {
		val !== getEditor()?.getValue() && updateMonacoVal(val);
	}
);
</script>

<style lang="scss" scoped>
.my-editor-area {
	position: relative;
	border-radius: 4px;
	overflow: hidden;
	padding: 5px;
	padding-left: 0;
	box-sizing: border-box;
	background-color: rgba(0, 0, 0, 0);
	:deep() {
		.margin,
		.monaco-editor,
		.inputarea.ime-input {
			background-color: rgba(0, 0, 0, 0);
		}

		.monaco-editor-background {
			background-color: rgba(0, 0, 0, 0);
		}
	}
}
</style>
